package com.edu.demo.service.impl;

import cn.hutool.core.lang.UUID;
import com.edu.demo.constant.CacheConstants;
import com.edu.demo.entity.LoginUser;
import com.edu.demo.exception.MyNullPointerException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: TokenService
 * @Description:
 * @Author: jxw
 * @Date: 2023-01-28
 */
@Component
@Slf4j
public class TokenService {

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret ;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成token,暴露接口
     * @param user
     * @return
     */
    public String createToken(LoginUser user){
        String token = UUID.fastUUID().toString(true);
        user.setToken(token);
        Map<String,Object> claims = new HashMap<>();
        claims.put(CacheConstants.LOGIN_USER_REDIS_KEY,token);
        refreshToken(user);
        return createToken(claims);
    }

    /**
     * 使用JWT生成token
     * @param claims
     * @return
     */
    private String createToken(Map<String,Object> claims){
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }


    /**
     * 解密token
     * @param token
     * @return
     */
    public Claims parseToken(String token){
       return  Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
       // claims.get(CacheConstants.LOGIN_USER_REDIS_KEY)
    }

    public void refreshToken(LoginUser user){
        long currentTimeMillis = System.currentTimeMillis();
        user.setLoginTime(currentTimeMillis);
        user.setExpireTime(currentTimeMillis+expireTime * 1000*60);
        String redisKey = CacheConstants.LOGIN_USER_REDIS_KEY+user.getToken();
        redisTemplate.opsForValue().set(redisKey,user,expireTime, TimeUnit.MINUTES);
    }

    public LoginUser getLoginUser(HttpServletRequest request) throws MyNullPointerException{
      //  String authentication = request.getHeader("Authentication");
        String token = request.getHeader(this.header);
        String header = request.getHeader("aaaaa");
        token = token.replace(CacheConstants.TOKEN_PREFIX,"");
        if(Strings.isNotBlank(token)){
            Claims claims = parseToken(token);
            String uuid = claims.get(CacheConstants.LOGIN_USER_REDIS_KEY, String.class);
            LoginUser user = (LoginUser) redisTemplate.opsForValue().get(CacheConstants.LOGIN_USER_REDIS_KEY + uuid);
            return user;
        }

        return null;
    }

    public void verifyToken(LoginUser loginUser) {
        log.info("loginUser.getExpireTime()-loginUser.getLoginTime()"+(loginUser.getExpireTime()-loginUser.getLoginTime())/60000);
        if(loginUser.getExpireTime()-loginUser.getLoginTime()<=20 * 60 * 1000L){

            refreshToken(loginUser);
        }
    }
}
